// -----------------------------
// Author: 		Dhaenens Gert	
// Creation: 	2/21/2015 12:56:03 AM				
// -----------------------------

#include "TextureManager.h"

#include "Engine.h"
#include "FileManager.h"
#include "FilePackage.h"

#include "PlatformProvider.h"

#include "ITexture.h"
#include "TextureLoader.h"

#include "Sprite.h"

namespace Flow
{

	TextureManager::TextureManager(IGraphicsDevice* lpDevice, IMutex* lpGraphicsMutex)
		: m_lpGraphicsDevice(lpDevice)
		, m_lpGraphicsMutex(lpGraphicsMutex)
	{
		TextureLoader::LoadLock();

		Sprite::s_lpTextures = this;
	}

	TextureManager::~TextureManager()
	{
		for (auto pair : m_Textures)
			pair.second->Release();

		TextureLoader::UnloadLock();

		Sprite::s_lpTextures = nullptr;
	}


	ITexture* TextureManager::LoadTexture(const tstring& file)
	{
		if (m_Textures.count(file) > 0)
			return m_Textures.at(file);

		TextureLoader* lpLoader = new TextureLoader(m_lpGraphicsDevice, m_lpGraphicsMutex, file);
		ITexture* lpTexture = lpLoader->Load();
		m_Textures.insert(make_pair(file, lpTexture));

		return nullptr;
	}
	ITexture* TextureManager::GetTexture(const tstring& file, Bool loadIfNotFound)
	{
		if (m_Textures.count(file) < 1)
		{
			if (loadIfNotFound)
				return LoadTexture(file);
		}
		else
			return m_Textures.at(file);

		return nullptr;
	}

}